package com.zat.mes.andrmes.dofun.qualitytest

import android.text.TextUtils
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.customerview.BottomSignCommDialog
import com.zat.mes.andrmes.customerview.BottomSignDailog
import com.zat.mes.andrmes.data.*
import com.zat.mes.andrmes.dofun.qualitytest.adapter.OnSiteDetailAdapter
import com.zat.mes.andrmes.dofun.qualitytest.vm.QcPlanViewModel
import com.zat.mes.andrmes.dofun.work.vm.WorkViewModel
import com.zat.mes.andrmes.event.QcRecordUpdateEventMessage
import com.zat.mes.andrmes.event.TodoEventMessage
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.global.CompanionType.Companion.INTENT_EXTRA_QCID
import com.zat.mes.andrmes.utils.PreferencesUtil
import com.zat.mes.andrmes.utils.SpannableStrUtil
import com.zat.mes.andrmes.utils.showToast
import kotlinx.android.synthetic.main.activity_deal_on_site.*
import kotlinx.android.synthetic.main.layout_title.*
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject

/**
 * 班组长处理巡检详情
 */
class DealOnSiteHasActivity : BaseActivity(), View.OnClickListener {


    private var workViewModel: WorkViewModel? = null
    private var empId: Long = 0
    private var empName: String = ""
    private var onSiteDetailAdapter: OnSiteDetailAdapter? = null
    private var qcPlanViewModel: QcPlanViewModel? = null
    var qcId: Long = 0
    var listDealWith: MutableList<ParantTypeItem>? = null
    var listEmp: MutableList<EmpBeanItem>? = null
    var select = -1
    /**
     * 处理方式
     */
    var dealWithStr = ""
    //返修人员id
    var repairEmpId: Long = 0
    //返修人员name
    var repairEmpName: String = ""

    override fun init() {
        initView()
        iniData()
        loadModel()
    }

    /**
     * 加载质检计划model
     */
    private fun loadModel() {
        qcPlanViewModel = ViewModelProvider(this).get(QcPlanViewModel::class.java)
        qcPlanViewModel?.getQcDetailData()?.observe(this, Observer {
            closeLoading()
            if (it != null) {
                setNewData(it)
                //查询班组下的所有人员
                workViewModel?.loadClassEmpList(1, Int.MAX_VALUE, it.classId, "2020-02-22", false)
            }


        })
        qcPlanViewModel?.selectQcRecordById(qcId)
        showLoading()

        qcPlanViewModel?.getParantTypeData()?.observe(this, Observer {
            if (it != null) {
                if (it.containsKey(CompanionType.QC_TREATMENT)) {
                    //处理方式
                    listDealWith = it.get(CompanionType.QC_TREATMENT)
                }
            }
        })
        qcPlanViewModel?.loadParantTypeList(CompanionType.QC_TREATMENT)

        qcPlanViewModel?.getInsertData()?.observe(this, Observer {
            closeLoading()
            android.os.Handler().postDelayed(Runnable {
                EventBus.getDefault().post(QcRecordUpdateEventMessage())
                EventBus.getDefault().post(TodoEventMessage())
                showToast(it)
                finish()
            }, 500)

        })

        workViewModel = ViewModelProvider(this).get(WorkViewModel::class.java)
        workViewModel?.getEmpList()?.observe(this, Observer {
            listEmp = it
        })

    }

    /**
     * 设置数据
     */
    private fun setNewData(bean: QcRecordHasBean) {
        if(!TextUtils.isEmpty(bean.ngdeal)){
            tvDealWith.text = bean.ngdeal
            dealWithStr = bean.ngdeal
        }

        val list: MutableList<KvBean> = ArrayList()
        val kv1 = bean?.productName?.let {
            KvBean(
                getString(R.string.produce_name),
                it
            )
        }
        kv1?.let { list.add(it) }
        val kv2 = bean?.styleNo?.let {
            KvBean(
                getString(R.string.text_style),
                it
            )
        }
        kv2?.let { list.add(it) }
        val kv3 = bean?.color?.let { KvBean(getString(R.string.text_color), it) }
        kv3?.let { list.add(it) }
        val kv4 = bean?.size?.let { KvBean(getString(R.string.text_size), it) }
        kv4?.let { list.add(it) }
        val kv5 = bean?.procName?.let {
            KvBean(
                getString(R.string.text_proc),
                it
            )
        }
        kv5?.let { list.add(it) }
        val kv6 = bean?.workshopName?.let {
            KvBean(
                getString(R.string.text_workshop),
                it
            )
        }
        kv6?.let { list.add(it) }
        val kv7 = bean?.className?.let {
            KvBean(
                getString(R.string.text_class),
                it
            )
        }
        kv7?.let { list.add(it) }
        val kv8 = bean?.workEmpName?.let {
            KvBean(
                getString(R.string.text_peple),
                it
            )
        }
        kv8?.let { list.add(it) }
        val kv9 =
            KvBean(getString(R.string.text_amount), bean?.quantity.toString())
        list.add(kv9)
        val kv10 =
            KvBean(getString(R.string.check_amount), bean?.qcQty.toString())
        list.add(kv10)
        val kv11 =
            KvBean(getString(R.string.bad_produce_amount), bean?.ngqty.toString())
        list.add(kv11)

        if (bean?.bodypartName != null) {
            val kv12 =
                KvBean(getString(R.string.body_path), bean?.bodypartName?.toString())
            list.add(kv12)
        }
        if ("1" == bean?.result) {
            val kv13 = KvBean(getString(R.string.qc_result), getString(R.string.hege))
            list.add(kv13)
        } else {
            val kv13 = KvBean(getString(R.string.qc_result), getString(R.string.hege_no))
            list.add(kv13)
        }
        var kv14 = KvBean(getString(R.string.buchongshuoming), "")
        if (!TextUtils.isEmpty(bean?.remark1)) {
            kv14.value = bean?.remark1
        }
        list.add(kv14)

        var kv15 = KvBean(getString(R.string.bad_result),"")
        if(!TextUtils.isEmpty(bean?.ngreason)){
            kv15.value = bean?.ngreason
            list.add(kv15)
        }
        var kv16 = KvBean(getString(R.string.deal_method_2),"")
        if(!TextUtils.isEmpty(bean?.ngdeal)){
            kv16.value = bean?.ngdeal
            list.add(kv16)
        }

        onSiteDetailAdapter?.setNewData(list)


    }

    /**
     * 数初始化
     */
    private fun iniData() {

        val loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        empId = loginResultBean.empid
        empName = loginResultBean.empname

        qcId = intent.getLongExtra(INTENT_EXTRA_QCID, 0)
        onSiteDetailAdapter = OnSiteDetailAdapter(R.layout.item_de_approve)
        ryDealOnSiteDetailHas.layoutManager = LinearLayoutManager(this)
        ryDealOnSiteDetailHas.adapter = onSiteDetailAdapter


    }


    private fun initView() {
        setContentView(R.layout.activity_deal_on_site)
        tVtitle.text = getString(R.string.title_deal_onsit_has)
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener { finish() }

        llDealWith.setOnClickListener(this)
        llRepairEmp.setOnClickListener(this)
        btnSaveRepair.setOnClickListener(this)

        tvNameDealWith.setText(
            SpannableStrUtil.getColorSpannable(
                getString(R.string.text_deal_method),
                0,
                1,
                ContextCompat.getColor(this, R.color.color_text_red)
            )
        )
        tvFineMoney.setText(
            SpannableStrUtil.getColorSpannable(
                getString(R.string.text_withhold_money),
                0,
                1,
                ContextCompat.getColor(this, R.color.color_text_red)
            )
        )

        tvRepairEmp.setText(
            SpannableStrUtil.getColorSpannable(
                getString(R.string.text_repair_peple),
                0,
                1,
                ContextCompat.getColor(this, R.color.color_text_red)
            )
        )
        tvDisuseQty.setText(
            SpannableStrUtil.getColorSpannable(
                getString(R.string.text_delete_amount),
                0,
                1,
                ContextCompat.getColor(this, R.color.color_text_red)
            )
        )
        tvRepairQty.setText(
            SpannableStrUtil.getColorSpannable(
                getString(R.string.text_repair_amount),
                0,
                1,
                ContextCompat.getColor(this, R.color.color_text_red)
            )
        )
    }

    override fun onClick(v: View?) {
        when (v) {
            llDealWith -> {
                //处理方式
                showBottomDialog(listDealWith)
            }
            llRepairEmp -> {
                //人员列表
                showEmpDialog(listEmp)
            }
            btnSaveRepair -> {
                if (TextUtils.isEmpty(tvDealWith.text.toString())) {
                    showToast(getString(R.string.text_select_deal_with))
                    return
                }
                if (TextUtils.isEmpty(etFineMoney.text.toString())) {
                    showToast(getString(R.string.text_input_money))
                    return
                }
                if (TextUtils.isEmpty(tvRepairEmpName.text.toString())) {
                    showToast(getString(R.string.text_select_repair_peple))
                    return
                }
                if (TextUtils.isEmpty(etDisuseQty.text.toString())) {
                    showToast(getString(R.string.text_input_delete_amount))
                    return
                }
                if (TextUtils.isEmpty(etRepairQty.text.toString())) {
                    showToast(getString(R.string.text_input_repair_amount))
                    return
                }

                //传参数据
                val jsonObject = JSONObject()
                jsonObject.put("qcId", qcId)
                jsonObject.put("treatment", dealWithStr)
                jsonObject.put("fineAmt", etFineMoney.text.toString())
                jsonObject.put("repairEmpId", repairEmpId)
                jsonObject.put("repairEmpName", repairEmpName)
                jsonObject.put("repairQty", etRepairQty.text.toString())
                jsonObject.put("disuseQty", etDisuseQty.text.toString())
                jsonObject.put("remark2", etRemark.text.toString())
                jsonObject.put("reviewEmpId", empId)
                jsonObject.put("reviewEmpName", empName)
                qcPlanViewModel?.upDateQcRecord(jsonObject.toString())
                showLoading()

            }
        }
    }

    /**
     * 显示底部弹框 处理方式
     */
    fun showBottomDialog(list: MutableList<ParantTypeItem>?) {
        BottomSignDailog(this, list, object : BottomSignDailog.OnBottomSelectListener {
            override fun onBottomSelect(parantTypeItem: ParantTypeItem) {
                tvDealWith.text = parantTypeItem.typename
                dealWithStr = parantTypeItem.typename
            }

        })
    }

    /**
     * 选择人员
     */
    fun showEmpDialog(list: MutableList<EmpBeanItem>?) {
        val strList: MutableList<String> = ArrayList()
        if (list != null) {
            for (emp in list) {
                strList.add(emp.empname)
            }
        }
        BottomSignCommDialog(this, strList,select, object : BottomSignCommDialog.OnBottomSelectListener {
            override fun onBottomSelect(position: Int) {
                tvRepairEmpName.text = list?.get(position)?.empname
                repairEmpId = list?.get(position)?.empid!!
                repairEmpName = list?.get(position)?.empname
                select = position
            }

        })
    }


}
